package com.wjw.redis.stream.config;

import com.alibaba.fastjson.JSONObject;
import com.wjw.redis.stream.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.stream.StreamListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author ：wjw
 * &#064;date  ：Created in 2022/5/19 10:15
 * &#064;description：消费监听，自动ack
 */
@Slf4j
@Component
public class ConsumeListener1 implements StreamListener<String, MapRecord<String, String, String>>, InitializingBean {

    @Autowired
    private RedisUtil redisUtil;
    private static ConsumeListener1 consumeListener1;

    @Override
    public void onMessage(MapRecord<String, String, String> message) {
        try {
            String stream = message.getStream();
            RecordId id = message.getId();
            Map<String, String> map = message.getValue();
            log.info("[不自动ack] group:[group-a] consumerName:[{}] 接收到一个消息 stream:[{}],id:[{}],value:[{}]", "group-a", stream, id, map);
            long result = consumeListener1.redisUtil.ack(stream, "group-a", id.getValue());
            log.info("ConsumeListener1 ack结果：{}", result);
//        long result1 = consumeListener1.redisUtil.del(stream, id.getValue());
//        log.info("ConsumeListener1 删除{}结果：{}", id, result1);
        } catch (Exception e) {
            log.error("处理消息时发生异常", e);
        }
    }

    @Override
    public void afterPropertiesSet() {
        consumeListener1 = this;
        consumeListener1.redisUtil = this.redisUtil;
    }
}
